<template>
  <el-card>
    <div slot="header">
      <h3>临时项目商品-编辑</h3>
    </div>
    <div class="project_goods_edit">
      <el-form style="width: 80%">
        <el-form-item label="提交说明：" label-width="90px">
          <el-input
            type="textarea"
            resize="none"
            v-model.trim="formData.updateExplain"
            show-word-limit
            placeholder="请输入提交说明"
            :autosize="{ minRows: 4 }"
            :maxlength="200"
          />
        </el-form-item>
      </el-form>
      <el-row>
        <skus-table
          ref="skusTable"
          showActionCol
          showSelectCol
          :tableHeight="480"
          :defaultMinWidth="100"
          :dataSource="tableInfo.list"
          :columns="tableInfo.columns"
          :loading="tableInfo.loading"
          :pageSizes="pageSizes"
          :pagination="pagination"
          :total="pagination.total"
          :selectionChange="handleSelectionChange"
          :actionRender="renderTableBtnAction"
          @pageChange="handlePageChange"
          @pageSizeSelect="handlePageSizeChange"
        >
          <div slot="content_context">
            <!-- 按钮操作栏 -->
            <BtnRender :render="renderBtnsBar" />
          </div>
        </skus-table>
      </el-row>
      <TableFooter :data-source="operInfo" />
    </div>
    <!-- 关联四级类弹框 -->
    <AssociatedDialog
      dialogTitle="关联四级类"
      currentType="1"
      :visible.sync="dialogVisible.category"
      @getSelectResults="getSelectCategory"
    />
    <!-- 关联品牌弹框 -->
    <AssociatedDialog
      dialogTitle="关联品牌"
      currentType="2"
      :visible.sync="dialogVisible.brand"
      @getSelectResults="getSelectBrand"
    />
    <!-- 关联计量单位弹框 -->
    <AssociatedDialog
      dialogTitle="关联计量单位"
      currentType="3"
      :visible.sync="dialogVisible.unit"
      @getSelectResults="getSelectUnit"
    />
  </el-card>
</template>
<script>
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import { getBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { TABLE_COLUMNS, ERROR_COL, CacheKey } from './constants/edit';
import AssociatedDialog from '../components/AssociatedDialog';
import TableFooter from '../components/TableFooter';
import {
  querySubmittedInfoService,
  submitUpdateInfoService
} from '@/api/commodity/temporaryPurchasingGoods/temporaryProjectGoods';
import skusPage from '@/mixins/commodity/skusPage';
import { removeSessionByRoute } from '@/utils/bizUtils';
export default {
  mixins: [skusPage],
  components: {
    BtnRender,
    SkusTable,
    AssociatedDialog,
    TableFooter
  },
  data () {
    return {
      formData: {
        updateExplain: ''
      },
      // 表格信息
      tableInfo: {
        list: [],
        columns: [],
        selection: [],
        loading: false
      },
      dialogVisible: {
        category: false,
        brand: false,
        unit: false
      },
      btnLoading: {
        submit: false
      },
      operInfo: {}
    }
  },
  mounted () {
    this.initAllData();
  },
  beforeRouteLeave (to, from, next) {
    removeSessionByRoute({
      toName: to.name,
      notRemoveNames: 'temporaryProjectGoodsEdit',
      cacheKey: CacheKey
    });
    next();
  },
  computed: {
    hasNoSelection () {
      return this.tableInfo.selection.length === 0;
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const disabled = this.hasNoSelection;
      const finalBar = [
        { label: '返回', method: this.handleGoBack },
        { label: '更换品类', method: this.handleLinkCategory, disabled },
        { label: '更换品牌', method: this.handleLinkBrand, disabled },
        { label: '更换计量单位', method: this.handleLinkUnit, disabled },
        { label: '提交', method: this.handleSubmit, loading: this.btnLoading.submit }
      ];
      // 按钮通用属性填充
      const btnsBar = finalBar.map(item => ({ ...item, type: 'default', size: 'mini', hasAuth: false }));
      return getBtnsBar(h, btnsBar, this.showBtn);
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [{ label: '取消修改', method: this.handleCancelEdit }];
      return getTableAction({ h, row, actionList });
    },
    // 返回
    handleGoBack () {
      this.goToListPage();
    },
    // 关联品类
    handleLinkCategory () {
      this.dialogVisible.category = true;
    },
    // 关联品牌
    handleLinkBrand () {
      this.dialogVisible.brand = true;
    },
    // 关联计量单位
    handleLinkUnit () {
      this.dialogVisible.unit = true;
    },
    // 提交
    handleSubmit () {
      this.submitEditInfo();
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 取消修改
    handleCancelEdit (row) {
      this.$confirm('确定要删除吗？', '删除', {
        type: 'warning',
      }).then(() => {
        this.tableInfo.list = this.tableInfo.list.filter(item => item.uuid !== row.uuid);
      }).catch(() => {});
    },
    // 初始化所有数据
    initAllData () {
      this.setTableColumns();
      this.getHistoryInfo();
    },
    // 获取选择品类结果
    getSelectCategory (results) {
      this.setTableRelativeInfo({
        categoryUuid: results?.categoryUuid,
        categoryName: results?.categoryName,
        categoryNo: results?.categoryNo
      });
    },
    // 获取选择品牌结果
    getSelectBrand (results) {
      this.setTableRelativeInfo({
        // otherBrand: results.otherBrandName,
        brandName: results.brandName,
        brandUuid: results.brandUuid
      });
    },
    // 获取选择计量单位结果
    getSelectUnit (results) {
      this.setTableRelativeInfo({
        unitId: results.unitUuid,
        unitNo: results.unitNo,
        unitName: results.unitName
      });
    },
    // 设置已勾选表格相关信息
    setTableRelativeInfo (data) {
      this.tableInfo.selection.forEach(item => {
        const index = this.tableInfo.list.findIndex(cur => item.uuid === cur.uuid);
        if (index === -1) return false;
        for (const key in data) {
          this.tableInfo.list[index][key] = data[key];
        }
      });
    },
    // 设置表列
    setTableColumns (headerColumns = []) {
      this.tableInfo.columns = _.cloneDeep([...headerColumns, ...TABLE_COLUMNS]);
    },
    // 获取历史数据
    async getHistoryInfo () {
      const uuids = sessionStorage.getItem(CacheKey);
      const res = await querySubmittedInfoService(uuids, '.project_goods_edit');
      if (res) {
        this.tableInfo.list = res.retData;
        const { operName, opeTime, operDeptName } = res.retData[0];
        this.operInfo = { operName, opeTime, operDeptName };
      }
    },
    // 提交临时项目商品编辑数据
    async submitEditInfo () {
      const loadingFn = state => { this.btnLoading.submit = state };
      const data = {
        ...this.formData,
        mds: this.tableInfo.list
      }
      const res = await submitUpdateInfoService(data, loadingFn);
      if (!res) return false;
      const { errorList } = res.retData;
      const hasSuccessed = errorList.length === 0;
      if (hasSuccessed) {
        this.$message.success('编辑成功');
        this.goToListPage();
      } else {
        this.setTableColumns(ERROR_COL);
        this.tableInfo.list = errorList;
        this.$message.warning('编辑失败，请查看异常信息');
      }
    },
    // 返回列表页
    goToListPage () {
      this.$router.push({ name: 'temporaryProjectGoodsList' });
    }
  }
}
</script>
